package com.bitcat.firstapp.demo.musicdemo

import android.app.Service
import android.content.Intent
import android.media.MediaPlayer
import android.os.Binder
import android.os.IBinder

class MusicService : Service() {

    private val musicBinder = MusicBinder()

    private var mediaPlayer:MediaPlayer? = null

    override fun onBind(intent: Intent): IBinder {
        return musicBinder
    }

    inner class MusicBinder:Binder(){
        fun getMusicService():MusicService{
           return this@MusicService
        }
    }

    override fun onCreate() {
        super.onCreate()
        mediaPlayer = MediaPlayer()
        mediaPlayer!!.setOnCompletionListener {
            //播放完成
            sendBroadcast(Intent("MUSIC_END"))
        }
    }

    override fun onDestroy() {
        mediaPlayer?.release()
        mediaPlayer = null
        super.onDestroy()
    }


    private var path:String? = null

    //播放音乐
    fun playMusic(path:String){
        if (this.path != path){
            this.path = path
            mediaPlayer?.apply {
                reset() //重置播放器
                setDataSource(path)
                prepare()
                start()
            }
        }

    }

    //暂停音乐
    fun pauseMusic(){
        //播放中才暂停
        if (mediaPlayer?.isPlaying == true){
            mediaPlayer?.pause()
        }
    }

    // 继续播放音乐
    fun resumeMusic(){
        if (mediaPlayer?.isPlaying == false){
            mediaPlayer?.start()
        }
    }

    // 获取播放状态
    fun isPlaying():Boolean = mediaPlayer?.isPlaying ?: false

    //获取音乐的总时长
    fun getDuration():Int = mediaPlayer?.duration ?: 0

    //获取当前播放进度
    fun getCurrentPosition():Int = mediaPlayer?.currentPosition ?: 0


    //跳转到指定位置
    fun seekTo(position:Int){
        mediaPlayer?.seekTo(position)
    }
}